class Draw2D {
	stationList: any[];
	segmentList: any[];
	areaList: any[];
	constructor(options: any) {
		const {
			id,
			options: { stationList, segmentList, areaList },
		} = options;
		this.stationList = stationList;
		this.segmentList = segmentList;
		this.areaList = areaList;
		// 创建2D地图
		const mapCanvas = document.getElementById(id) as HTMLCanvasElement;
		const mapCtx = mapCanvas.getContext("2d") as CanvasRenderingContext2D;
		mapCanvas.width = mapCanvas.clientWidth;
		mapCanvas.height = mapCanvas.clientHeight;
		requestAnimationFrame(() => {
			console.log(mapCtx);
			this.drawStation(mapCtx);
			this.drawSegment(mapCtx);
			// 放大两倍
			mapCtx.scale(20, -20);
			// 原点切换到中心
			this.centerMap(mapCtx, mapCanvas);
		});
	}
	// 地图根据屏幕大小居中
	centerMap(mapCtx: CanvasRenderingContext2D, mapCanvas: HTMLCanvasElement) {
		const { width, height } = this.getMapSize();
		const centerX = (mapCanvas.width - width) / 2;
		const centerY = (mapCanvas.height - height) / 2;
		console.log(centerX, centerY);
		mapCtx.translate(centerX, centerY);
	}
	// 计算地图的宽度和高度
	getMapSize() {
		const { minX, minY, maxX, maxY } = this.getBoundary();
		const width = Math.abs(maxX - minX);
		const height = Math.abs(maxY - minY);
		return {
			width,
			height,
		};
	}
	// 得到左上角和右下角的点
	getBoundary() {
		let minX = Number.MAX_VALUE;
		let minY = Number.MAX_VALUE;
		let maxX = Number.MIN_VALUE;
		let maxY = Number.MIN_VALUE;
		this.stationList.forEach((station) => {
			minX = Math.min(minX, station.x);
			minY = Math.min(minY, station.y);
			maxX = Math.max(maxX, station.x);
			maxY = Math.max(maxY, station.y);
		});
		return {
			minX,
			minY,
			maxX,
			maxY,
		};
	}
	drawStation(mapCtx: CanvasRenderingContext2D) {
		// 绘制点
		mapCtx.strokeStyle = "red";
		this.stationList.forEach((station) => {
			mapCtx.beginPath();
			mapCtx.arc(station.x, station.y, 0.1, 0, Math.PI * 2);
			mapCtx.fill();
			mapCtx.closePath();
		});
	}
	drawSegment(mapCtx: CanvasRenderingContext2D) {
		this.segmentList.forEach((segment) => {
			const { degree, controlPoints } = segment.trajectory;

			// 绘制直线
			if (degree === 1) {
				mapCtx.beginPath();
				mapCtx.strokeStyle = "red";
				mapCtx.lineWidth = 0.05;
				mapCtx.moveTo(controlPoints[0].x, controlPoints[0].y);
				mapCtx.lineTo(controlPoints[1].x, controlPoints[1].y);
				mapCtx.stroke();
			}
			// 绘制三次beizier曲线
			if (degree === 3) {
				mapCtx.beginPath();
				mapCtx.strokeStyle = "red";
				mapCtx.lineWidth = 0.05;
				mapCtx.moveTo(controlPoints[0].x, controlPoints[0].y);
				mapCtx.bezierCurveTo(
					controlPoints[1].x,
					controlPoints[1].y,
					controlPoints[2].x,
					controlPoints[2].y,
					controlPoints[3].x,
					controlPoints[3].y
				);
				mapCtx.stroke();
			}
		});
	}
}
export const twoD = (options: any) => {
	new Draw2D(options);
};
